package org.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.catalina.User;
import org.example.common.constants.Result;
import org.example.pojo.UserInfo;
import org.example.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class AdminController {


    @Autowired
    private UserInfoService userInfoService;



    @GetMapping("/index")
    public String adminIndex(){
        return "admin/index";
    }


    @GetMapping("/customer")
    public String customerList(Model model){
        List<UserInfo> userList = userInfoService.list();
        model.addAttribute("userList", userList);

        return "admin/customer_list";
    }


    @GetMapping("/customerAdd")
    public String customerAdd(Model model){
        UserInfo userInfo = new UserInfo();
        model.addAttribute("customer",userInfo);
        return "admin/customer_add";
    }


//    @ResponseBody
//    @GetMapping("/user/list")
//    public Result<List<UserInfo>> list() {
//        return Result.success(userInfoService.list());
//    }

    @PostMapping("/user/add")
    public String add(@ModelAttribute UserInfo userInfo) {
         userInfoService.save(userInfo);
         return "redirect:/admin/customer";
    }




    // UserInfoController.java

    @GetMapping("/user/edit/{id}")
    public String editUser(@PathVariable Long id, Model model) {
        UserInfo customer = userInfoService.getById(id);
        if (customer == null) {
            // 可以跳转到错误页面或返回404
            return "redirect:/admin/customer";
        }
        model.addAttribute("customer", customer);
        return "admin/customer_edit";
    }

    @PostMapping("/user/update")
    public String updateUser(@ModelAttribute UserInfo customer) {
        userInfoService.updateById(customer);
        return "redirect:/admin/customer";
    }


    @GetMapping("/user/delete/{id}")
    public String delete(@PathVariable Integer id) {
        boolean b = userInfoService.removeById(id);
        return "redirect:/admin/customer";
    }

//
//    @GetMapping("/user/list1")
//    public String listUsers(@RequestParam(required = false) String name,
//                            @RequestParam(required = false) String pid,
//                            Model model) {
//        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
//        if (StringUtils.hasText(name)) {
//            wrapper.like("name", name);
//        }
//        if (StringUtils.hasText(pid)) {
//            wrapper.like("pid", pid);
//        }
//
//        List<UserInfo> userList = userInfoService.list(wrapper);
//        model.addAttribute("userList", userList);
//        model.addAttribute("name", name);
//        model.addAttribute("pid", pid);
//        return "admin/customer_list";
//    }

    @GetMapping("/user/list")
    public String listUsers(@RequestParam(required = false) String customerName,
                            @RequestParam(required = false) String PID,
                            Model model) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if (StringUtils.hasText(customerName)) {
            wrapper.like("name", customerName);
        }
        if (StringUtils.hasText(PID)) {
            wrapper.like("pid", PID);
        }

        List<UserInfo> userList = userInfoService.list(wrapper);

        model.addAttribute("userList", userList);
        model.addAttribute("customerName", customerName);
        model.addAttribute("PID", PID);
        return "admin/customer_list";
    }

    @GetMapping("/user/export")
    public void exportCsv(HttpServletResponse response) throws IOException {
        List<UserInfo> users = userInfoService.list();

        // 设置响应头
        response.setContentType("text/csv; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        String fileName = URLEncoder.encode("客户信息表.csv", String.valueOf(StandardCharsets.UTF_8));
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        // 获取输出流
        ServletOutputStream outputStream = response.getOutputStream();

        // 写入 BOM 解决 Excel 中文乱码问题
        byte[] bom = {(byte)0xEF, (byte)0xBB, (byte)0xBF};
        outputStream.write(bom);

        // 写入 CSV 表头
        String header = "客户编号,客户姓名,身份证号,联系电话,联系地址\n";
        outputStream.write(header.getBytes(StandardCharsets.UTF_8));

        // 写入数据
        for (UserInfo user : users) {
            String row = user.getCustomerId() + "," +
                    user.getName() + "," +
                    user.getPid() + "," +
                    user.getTelephone() + "," +
                    user.getAddress() + "\n";
            outputStream.write(row.getBytes(StandardCharsets.UTF_8));
        }

        outputStream.flush();
        outputStream.close();
    }

}
